package com.wjy.sfhcore;

import android.app.Application;

import com.wjy.sfhcore.itf.OnNetStateChanged;
import com.wjy.sfhcore.itf.RxNetwork;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;

/**
 * Created by wangjingyuan on 15/6/4.
 */
public class CoreApplication extends Application {
    private static CoreApplication instance;
    private List<OnNetStateChanged> onNetStateChangedListenerList = new ArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        Observable<Boolean> sendStateStream = RxNetwork.stream(this).map(state -> {
            return state != RxNetwork.State.NOT_CONNECTED;
        });
        sendStateStream.subscribe(isConnect -> {
            onNetStateChanged(isConnect);
        });
    }

    public static CoreApplication getInstance() {
        return instance;
    }

    public void registerNetStateWatcher(OnNetStateChanged lLoadFragment) {
        if (onNetStateChangedListenerList != null)
            onNetStateChangedListenerList.add(lLoadFragment);
    }

    public void unRegisterNetStateWatcher(OnNetStateChanged lLoadFragment) {
        if (onNetStateChangedListenerList != null && onNetStateChangedListenerList.contains(lLoadFragment)) {
            onNetStateChangedListenerList.remove(lLoadFragment);
        }
    }

    /**
     * 处理网络状态的改变
     *
     * @param isConnect
     */
    private void onNetStateChanged(Boolean isConnect) {
        for (OnNetStateChanged item : onNetStateChangedListenerList) {
            item.onNetStateChanged(isConnect);
        }
    }
}
